package org.br.erp.rfq.xbj.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.br.erp.base.utils.ERPUtils;
import org.br.erp.rfq.quo.entity.Scmquotation;
import org.br.erp.rfq.quo.service.IScmquotationService;
import org.br.erp.rfq.xbj.vo.*;
import org.jeecg.modules.base.mapper.BaseCommonMapper;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.br.erp.rfq.xbj.entity.Scmxjditem;
import org.br.erp.rfq.xbj.entity.Scmxjd;
import org.br.erp.rfq.xbj.service.IScmxjdService;
import org.br.erp.rfq.xbj.service.IScmxjditemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 询价单
 * @Author: jeecg-boot
 * @Date:   2023-09-16
 * @Version: V1.0
 */
@Api(tags="询价单")
@RestController
@RequestMapping("/rfq.xbj/scmxjd")
@Slf4j
public class ScmxjdController {
	@Autowired
	private IScmxjdService scmxjdService;
	@Autowired
	private IScmxjditemService scmxjditemService;

	@Autowired
	private IScmquotationService scmquotationService;

	@Autowired
	private BaseCommonMapper baseCommonMapper;
	/**
	 * 分页列表查询
	 *
	 * @param scmxjd
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "询价单-分页列表查询")
	@ApiOperation(value="询价单-分页列表查询", notes="询价单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Scmxjd>> queryPageList(Scmxjd scmxjd,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Scmxjd> queryWrapper = QueryGenerator.initQueryWrapper(scmxjd, req.getParameterMap());
		Page<Scmxjd> page = new Page<Scmxjd>(pageNo, pageSize);

		IPage<Scmxjd> pageList = scmxjdService.getXjdList(page,queryWrapper);
		return Result.OK(pageList);
	}



	/**
	 *   添加
	 *
	 * @param scmxjdPage
	 * @return
	 */
	@AutoLog(value = "询价单-添加")
	@ApiOperation(value="询价单-添加", notes="询价单-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ScmxjdPage scmxjdPage ) {
		Scmxjd scmxjd = new Scmxjd();
		BeanUtils.copyProperties(scmxjdPage, scmxjd);
		scmxjdService.saveMain(scmxjd, scmxjdPage.getScmxjditemList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param scmxjdPage
	 * @return
	 */
	@AutoLog(value = "询价单-编辑")
	@ApiOperation(value="询价单-编辑", notes="询价单-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ScmxjdPage scmxjdPage) {
		Scmxjd scmxjd = new Scmxjd();
		BeanUtils.copyProperties(scmxjdPage, scmxjd);
		Scmxjd scmxjdEntity = scmxjdService.getById(scmxjd.getId());
		if(scmxjdEntity==null) {
			return Result.error("未找到对应数据");
		}
		scmxjdService.updateMain(scmxjd, scmxjdPage.getScmxjditemList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "询价单-通过id删除")
	@ApiOperation(value="询价单-通过id删除", notes="询价单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		scmxjdService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "询价单-批量删除")
	@ApiOperation(value="询价单-批量删除", notes="询价单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.scmxjdService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "询价单-通过id查询")
	@ApiOperation(value="询价单-通过id查询", notes="询价单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Scmxjd> queryById(@RequestParam(name="id",required=true) String id) {
		Scmxjd scmxjd = scmxjdService.getById(id);
		if(scmxjd==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(scmxjd);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "询价单分录通过主表ID查询")
	@ApiOperation(value="询价单分录主表ID查询", notes="询价单分录-通主表ID查询")
	@GetMapping(value = "/queryScmxjditemByMainId")
	public Result<List<Scmxjditem>> queryScmxjditemListByMainId(@RequestParam(name="id",required=true) String id) {
		List<Scmxjditem> scmxjditemList = scmxjditemService.selectByMainId(id);
		return Result.OK(scmxjditemList);
	}

	@GetMapping(value = "/queryScmxjditemByMainIdNew")
	public Result<List<ScmXjdItemNewVo>> queryScmxjdItemListByMainIdNew(@RequestParam(name = "id",required = true) String id,HttpServletRequest httpServletRequest){
		List<Scmxjditem> scmxjditems = scmxjditemService.selectByMainId(id);
		List<ScmXjdItemNewVo> scmXjdItemNewVos=new ArrayList<>();

		Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();

		String vendorid = "";
		if(ERPUtils.ifHtppReqParamContainKey(parameterMap,"vendorid")){
			vendorid = ERPUtils.getHttpReqParam(parameterMap,"vendorid");
		}

		String selecttablevalue ="";
    if (vendorid.equalsIgnoreCase("")) {
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();


		selecttablevalue= baseCommonMapper.selecttablevalue("sys_user", "innervendorid", "id", sysUser.getId());

      if (selecttablevalue == null || selecttablevalue.equalsIgnoreCase("")) {
        throw new RuntimeException("当前用户没有定义报价供应商");
      }
}

		for (Scmxjditem scmxjditem : scmxjditems) {
			String quality = scmxjditem.getQuality();
			String[] split = quality.split(",");
			if(split.length>0){
				for (String s : split) {
					ScmXjdItemNewVo scmXjdItemNewVo=new ScmXjdItemNewVo();
					BeanUtils.copyProperties(scmxjditem,scmXjdItemNewVo);
					scmXjdItemNewVo.setQuality(s);
					scmXjdItemNewVo.setItemid(scmxjditem.getParentid()+"&"+scmxjditem.getId()+"&"+s);


					QueryWrapper<Scmquotation> queryWrapper=new QueryWrapper<>();
					queryWrapper.eq("fromitemid",scmxjditem.getId());
					if(!vendorid.equalsIgnoreCase("")){
						queryWrapper.eq("vendorid",vendorid);
          } else {
            queryWrapper.eq("vendorid", selecttablevalue);
					}
					queryWrapper.eq("quality",s);
					queryWrapper.eq("quostate","1");
					List<Scmquotation> list = scmquotationService.list(queryWrapper);
					if(list.size()>0){
						scmXjdItemNewVo.setQuoprice(list.get(0).getQuoprice());
						scmXjdItemNewVo.setQuoremarks(list.get(0).getQuoremarks());
						scmXjdItemNewVo.setQuotaxinvalue(list.get(0).getQuovalue());
						scmXjdItemNewVo.setQuoid(list.get(0).getId());
					}else{
						scmXjdItemNewVo.setQuoprice(BigDecimal.ZERO);
						scmXjdItemNewVo.setQuoremarks("");
						scmXjdItemNewVo.setQuotaxinvalue(BigDecimal.ZERO);
						scmXjdItemNewVo.setQuoid("");
					}
					scmXjdItemNewVos.add(scmXjdItemNewVo);
				}
			}
		}
		return Result.OK(scmXjdItemNewVos);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param scmxjd
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Scmxjd scmxjd) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<Scmxjd> queryWrapper = QueryGenerator.initQueryWrapper(scmxjd, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<Scmxjd> scmxjdList = scmxjdService.list(queryWrapper);

      // Step.3 组装pageList
      List<ScmxjdPage> pageList = new ArrayList<ScmxjdPage>();
      for (Scmxjd main : scmxjdList) {
          ScmxjdPage vo = new ScmxjdPage();
          BeanUtils.copyProperties(main, vo);
          List<Scmxjditem> scmxjditemList = scmxjditemService.selectByMainId(main.getId());
          vo.setScmxjditemList(scmxjditemList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "询价单列表");
      mv.addObject(NormalExcelConstants.CLASS, ScmxjdPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("询价单数据", "导出人:"+sysUser.getRealname(), "询价单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ScmxjdPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ScmxjdPage.class, params);
              for (ScmxjdPage page : list) {
                  Scmxjd po = new Scmxjd();
                  BeanUtils.copyProperties(page, po);
                  scmxjdService.saveMain(po, page.getScmxjditemList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	@PostMapping(value = "submitxjd")
	public Result<String> submitXJD(@RequestBody JSONObject jsonObject){
		//List<Map> id = JSON.parseArray(jsonObject.get("id"), Map.class);
		ArrayList<Map> res = (ArrayList)jsonObject.get("id");
		scmxjdService.updateXJDStatus(res);
		return Result.ok("更新成功");
	}

	@PostMapping(value = "updatevendor")
	public Result<String> updateVendor(@RequestBody JSONObject jsonObject){
		ArrayList<Map> reu = (ArrayList<Map>) jsonObject.get("id");
		scmxjdService.updatevendorid(reu);
		return Result.ok();
	}


	@GetMapping(value = "getvendorunquolist")
	public Result<IPage<ScmVendorUnQuoList>> getvendorUnQuoList( @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																 HttpServletRequest req){

		Map<String, String[]> parameterMap = req.getParameterMap();
		IPage<ScmVendorUnQuoList> page=new Page<>(pageNo,pageSize);
		QueryWrapper<ScmVendorUnQuoList> queryWrapper=new QueryWrapper<>();
		List<ScmVendorUnQuoList> scmVendorUnQuoLists = scmxjdService.selectVendorUnQuoList(page, queryWrapper);
		page.setRecords(scmVendorUnQuoLists);

		return Result.ok(page);
	}

	@GetMapping("/getxjdcomparelist")
	public Result<IPage<ScmXjdItemVo>> getXjdItemList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													  HttpServletRequest req){
		Map<String, String[]> parameterMap = req.getParameterMap();
		IPage<ScmXjdItemVo> page = new Page<>(pageNo,pageSize);
		QueryWrapper<ScmXjdItemVo> queryWrapper=new QueryWrapper<>();
		List<ScmXjdItemVo> xjdItemVo = scmxjditemService.getXjdItemVo(page, queryWrapper);
		page.setRecords(xjdItemVo);
		return Result.ok(page);
	}

	@PostMapping("getxzsinfo")
	public  Result<JSONObject> getXSZInfo(@RequestBody JSONObject jsonObject){
		String img = jsonObject.get("img").toString();
		JSONObject xszInfo = scmxjdService.getXSZInfo(img);
		return Result.ok(xszInfo);
	}


	@GetMapping(value = "getxjdvolist")
	public Result<IPage<ScmxjdVo>> getXJDVoList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												HttpServletRequest req){
		IPage<Scmxjd> page=new Page<>(pageNo,pageSize);
		QueryWrapper<Scmxjd> queryWrapper=new QueryWrapper<>();

		Map<String, String[]> parameterMap = req.getParameterMap();
		String bjdstatus="";
		if(ERPUtils.ifHtppReqParamContainKey(parameterMap,"bjdstatus")){
			 bjdstatus = ERPUtils.getHttpReqParam(parameterMap, "bjdstatus");

		}
		List<ScmxjdVo> vendorQuoList = scmxjdService.getVendorQuoList(page, bjdstatus);
		long total = page.getTotal();
		IPage<ScmxjdVo> res=new Page<>();
		res.setRecords(vendorQuoList);
		res.setTotal(total);
//		if(vendorQuoList.size() == 0){
//			return Result.error("");
//		}
		return Result.ok(res);
	}


	@GetMapping(value = "getwxdjvendorlistinfo")
	public Result<IPage<ScmxjdVo>> getVendorListInfo(Scmxjd scmxjd,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req){

		IPage<Scmxjd> page=new Page<>(pageNo,pageSize);
		Map<String, String[]> parameterMap = req.getParameterMap();
		QueryWrapper<Scmxjd> queryWrapper = QueryGenerator.initQueryWrapper(scmxjd, req.getParameterMap());
		List<ScmxjdVo> notPOXjdAndQuoList = scmxjdService.getNotPOXjdAndQuoList(page, "1",queryWrapper);

		long total = page.getTotal();

		IPage<ScmxjdVo> scmxjdVoIPage=new Page<>(pageNo,pageSize);
		scmxjdVoIPage.setRecords(notPOXjdAndQuoList);
		scmxjdVoIPage.setTotal(total);
		return Result.ok(scmxjdVoIPage);

	}

	@GetMapping(value = "getvendorinfo")
	public Result<JSONArray> getVendorInfo(HttpServletRequest httpServletRequest){

		Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
		if(ERPUtils.ifHtppReqParamContainKey(parameterMap,"xjdid")){
			String xjdid = ERPUtils.getHttpReqParam(parameterMap, "xjdid");
			JSONArray reqVendorInfo = scmxjdService.getReqVendorInfo(xjdid);
			return Result.ok(reqVendorInfo);
		}else{
			return Result.error(null);
		}
	}



}
